package com.yangfan.thread.thread_wangwenjun03;

/**
 * @description: 死锁
 * @author: yangfan
 * @date: Created in 2020/1/26 0026 18:59
 * @modified By:
 *
 *
 * 处于死锁状态 CPU 都不会有任何变化
 *
 * 如何去避免：尽量不要让程序中有多个锁层叠的这种关系
 *
 * 如果是 能看视图的话则 使用 jconsole 工具
 *
 * jps 查看当前 运行的线程 的线程
 *
 * jstack 线程ID
 *
 * jstack 效果如下
 *
 * Found one Java-level deadlock:
 * =============================
 * "Thread-1":
 *   waiting to lock monitor 0x00000000199fbba8 (object 0x0000000780b151e0, a java.lang.Object),
 *   which is held by "Thread-0"
 * "Thread-0":
 *   waiting to lock monitor 0x00000000199fa708 (object 0x0000000780b15208, a java.lang.Object),
 *   which is held by "Thread-1"
 *
 * Java stack information for the threads listed above:
 * ===================================================
 * "Thread-1":
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLockService.s1(DeadLockService.java:25)
 *         - waiting to lock <0x0000000780b151e0> (a java.lang.Object)
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLock.m1(DeadLock.java:26)
 *         - locked <0x0000000780b15208> (a java.lang.Object)
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLock.access$000(DeadLock.java:11)
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLock$2.run(DeadLock.java:65)
 * "Thread-0":
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLock.m2(DeadLock.java:34)
 *         - waiting to lock <0x0000000780b15208> (a java.lang.Object)
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLockService.s2(DeadLockService.java:35)
 *         - locked <0x0000000780b151e0> (a java.lang.Object)
 *         at com.yangfan.thread.thread_wangwenjunday03.DeadLock$1.run(DeadLock.java:53)
 *
 * Found 1 deadlock.
 *
 */
public class DeadLock {

    private final Object lock = new Object();

    DeadLock(DeadLockService deadLockService) {
        this.deadLockService = deadLockService;
    }

    private DeadLockService deadLockService;


    private void m1() {

        synchronized (lock){//先给自己加锁
            System.out.println("================m1================");
            deadLockService.s1();
        }

    }


    public void m2() {
        synchronized (lock){//需要先给自己加锁
            System.out.println("================m2================");
        }
    }


    public static void main(String[] args) {

        DeadLockService deadLockService = new DeadLockService();
        DeadLock deadLock = new DeadLock(deadLockService);
        deadLockService.setDeadLock(deadLock);

        Thread t1 = new Thread(){
            @Override
            public void run() {
                while(true){
                    deadLockService.s2();
                }

            }
        };
        t1.start();

        Thread t2 = new Thread(){
            @Override
            public void run() {
                while(true){
                    deadLock.m1();
                }

            }
        };
        t2.start();



    }






}
